package com.lzy.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzy.common.exception.Assert;
import com.lzy.common.result.ResponseEnum;
import com.lzy.srb.core.enums.BorrowAuthEnum;
import com.lzy.srb.core.enums.BorrowInfoStatusEnum;
import com.lzy.srb.core.enums.BorrowerStatusEnum;
import com.lzy.srb.core.enums.UserBindEnum;
import com.lzy.srb.core.mapper.BorrowerMapper;
import com.lzy.srb.core.mapper.IntegralGradeMapper;
import com.lzy.srb.core.mapper.UserInfoMapper;
import com.lzy.srb.core.pojo.entity.BorrowInfo;
import com.lzy.srb.core.mapper.BorrowInfoMapper;
import com.lzy.srb.core.pojo.entity.Borrower;
import com.lzy.srb.core.pojo.entity.IntegralGrade;
import com.lzy.srb.core.pojo.entity.UserInfo;
import com.lzy.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.lzy.srb.core.pojo.vo.BorrowerDetailVO;
import com.lzy.srb.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author lzy
 * @since 2023-02-23
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    IntegralGradeMapper integralGradeMapper;

    @Autowired
    BorrowInfoService borrowInfoService;

    @Autowired
    DictService dictService;

    @Autowired
    BorrowerMapper borrowerMapper;

    @Autowired
    BorrowerService borrowerService;

    @Autowired
    LendService lendService;

    @Override
    public BigDecimal getBorrowAmount(Long userId) {

        //获取用户积分
        UserInfo userInfo = userInfoService.getById(userId);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        Integer integral = userInfo.getIntegral();

        //根据计分查询额度
        QueryWrapper<IntegralGrade> wrapper = new QueryWrapper<>();
        wrapper.le("integral_start",integral).ge("integral_end",integral);
        IntegralGrade count = integralGradeMapper.selectOne(wrapper);
        if(count == null){
            return new BigDecimal("0");
        }else{
            return count.getBorrowAmount();
        }
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {

        //获取userInfo信息
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //判断用户绑定状态
        Assert.isTrue(userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus().intValue(),ResponseEnum.USER_NO_BIND_ERROR);

        //判断借款人额度申请状态
        Assert.isTrue(userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),ResponseEnum.USER_NO_AMOUNT_ERROR);

        //判断借款人额度是否充足
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        Assert.isTrue(borrowInfo.getAmount().doubleValue() <= borrowAmount.doubleValue(),ResponseEnum.USER_AMOUNT_LESS_ERROR);

        //存储borrowInfo数据
        borrowInfo.setUserId(userId);

        //百分比转小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));

        //设置借款申请的审核状态
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        baseMapper.insert(borrowInfo);

    }

    @Override
    public Integer getStatusByUserId(Long userId) {
        QueryWrapper<BorrowInfo> wrapper = new QueryWrapper<>();
        wrapper.select("status").eq("user_id",userId);
        List<Object> objectList = baseMapper.selectObjs(wrapper);
        if(objectList.size()==0){
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }else{
            Integer status = (Integer) objectList.get(0);
            return status;
        }
    }

    @Override
    public List<BorrowInfo> selectList() {
        List<BorrowInfo> borrowInfoList = baseMapper.selectBorrowInfoList();
        borrowInfoList.forEach(borrowInfo->{
            String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
            String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
            String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());

            borrowInfo.getParam().put("returnMethod",returnMethod);
            borrowInfo.getParam().put("moneyUse",moneyUse);
            borrowInfo.getParam().put("status",status);
        });
        return borrowInfoList;
    }

    @Override
    public Map<String, Object> getBorrowInfoDetail(Long id) {


        //查询借款对象：BorrowInfo
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());

        borrowInfo.getParam().put("returnMethod",returnMethod);
        borrowInfo.getParam().put("moneyUse",moneyUse);
        borrowInfo.getParam().put("status",status);


        //查询借款人对象：Borrower(BorrowerDetailVO)
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(wrapper);
        BorrowerDetailVO borrowInfoDetailVO = borrowerService.getBorrowerDetailVOById(borrower.getId());

        //组装集合结果
        Map<String,Object> result = new HashMap<>();
        result.put("borrowInfo",borrowInfo);
        result.put("borrower",borrowInfoDetailVO);
        return result;
    }

    @Override
    public void approval(BorrowInfoApprovalVO approvalVO) {

        //修改借款审核的状态 borrow_info
        Long borrowInfoId = approvalVO.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        borrowInfo.setStatus(approvalVO.getStatus());
        baseMapper.updateById(borrowInfo);

        //如果审核通过，则产生新的标的记录
        if(approvalVO.getStatus().intValue()==BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()){
            //产生新标的
            //TODO
            lendService.createLend(approvalVO,borrowInfo);
        }

    }
}
